package com.yang.sms.ali;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import lombok.extern.slf4j.Slf4j;
import org.yang.businesstool.sms.core.SendResponse;

import java.util.Optional;

/**
 * 阿里云短信客户端
 *
 * <pre>
 * 官方文档：https://help.aliyun.com/document_detail/419273.htm?spm=a2c4g.11186623.0.0.1f126cf0cAYBIr
 * </pre>
 * @author Billyang
 * @date 2024/9/29 10:04
 */
@Slf4j
public class SmsClient {

    private IAcsClient client;

    public SmsClient(String regionId,String accessKey,String secretKey) {
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKey, secretKey);
        this.client = new DefaultAcsClient(profile);
    }

    public SendResponse send(String mobile,String signName,String templateCode,String templateParam){
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(mobile);
        request.setSignName(signName);
        request.setTemplateCode(templateCode);
        request.setTemplateParam(templateParam);

        // 可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        // request.setOutId("yourOutId");

        SendResponse response = new SendResponse();
        try{
            SendSmsResponse acsResponse = client.getAcsResponse(request);
            log.info("ali sms response:{}",acsResponse);
            response.setRequestId(acsResponse.getRequestId());

            String code = acsResponse.getCode();
            if ("OK".equals(code)) {
                response.setSuccess(true);
            } else {
                response.setSuccess(false);
                response.setMessage(response.getMessage());
            }
        }catch (ServerException e){
            log.error("ServerException error", e);
            response.setSuccess(false);
            response.setMessage(Optional.ofNullable(e.getErrMsg()).orElse(e.getMessage()));
            response.setRequestId(e.getRequestId());
        }catch (ClientException e) {
            log.error("ClientException error", e);
            response.setSuccess(false);
            response.setMessage(Optional.ofNullable(e.getErrMsg()).orElse(e.getMessage()));
            response.setRequestId(e.getRequestId());
        }

        return response;
    }

}
